<template>
    <div class="Business">
        <div class="table">
            <Table border :columns="tableHead" :data="tableData" show-summary :summary-method="handleSummary">
                <template slot-scope="{ row, index}" slot="eliefDays">
                    <InputNumber :disabled="row._rowDisabled || Obj.readOnly || readOnly || row.status === 'settle'"
                                 v-model="row.eliefDays"
                                 :max="row.overdueDays"
                                 :min="0"
                                 :precision="0"
                                 @on-change="getReductionRatioAndExemptionAmt(row,index,'eliefDays')"/>
                </template>
                <!-- 减免比例 -->
                <template slot-scope="{ row, index }" slot="reductionRatio">
                    <InputNumber
                        :disabled="row._rowDisabled || Obj.readOnly|| readOnly || row.status === 'settle'"
                        :max="100"
                        v-model="row.reductionRatio"
                        :formatter="value => `${value}%`"
                        :parser="value => value.replace('%', '')"
                        :min="0"
                        @on-change="getReductionRatioAndExemptionAmt(row,index,'reductionRatio')"
                    ></InputNumber>
                </template>
                <!-- 豁免金额 -->
                <template slot-scope="{ row, index }" slot="exemptionAmt">
                    <InputNumber v-model="row.exemptionAmt"
                                 :disabled="row._rowDisabled || Obj.readOnly|| readOnly || row.status === 'settle'"
                                 @on-change="getReductionRatioAndExemptionAmt(row,index,'exemptionAmt')"
                                 :min="0"
                                 :max="row.penaltyAmt"
                    />
                </template>
                <!-- 净逾期额 -->
                <template slot-scope="{ row }" slot="overdueAmt">
                    <span>{{row.overdueAmt.toFixed(2)}}</span>
                </template>

                <!--小数点两位  -->
                <!-- 罚息总计 -->
                <template slot-scope="{ row }" slot="totalPenalty">
                    <span>{{row.totalPenalty.toFixed(2)}}</span>
                </template>
                <!-- 罚息金额 -->
                <template slot-scope="{ row }" slot="penaltyAmt">
                    <span>{{row.penaltyAmt.toFixed(2)}}</span>
                </template>
                <!-- 累计豁免额 -->
                <template slot-scope="{ row }" slot="exemptedAmt">
                    <span>{{row.exemptedAmt.toFixed(2)}}</span>
                </template>
                <!-- 核销额 -->
                <template slot-scope="{ row }" slot="receivedAmt">
                    <span>{{row.receivedAmt.toFixed(2)}}</span>
                </template>
                <!-- 类型 -->
                <template slot-scope="{ row }" slot="status">
                    <span>{{getTitle('expeenseStatus',row.status)}}</span>
                </template>
            </Table>
            <Row class="table-foot">
                <!-- TODO 总计 -->
                <Col span="20">总计: 罚息、豁免金额、核销额、净逾期额</Col>
            </Row>
        </div>

        <br>
        <Form ref="formData" :model="formData" :rules="formRules" :label-width="110">
            <Row>
                <!-- 罚息总计 -->
                <Col :xs="24" :md="12" :lg="8">
                    <FormItem label="罚息总计">
                        <InputNumber style="width: 200px" disabled v-model="formData.totalPenalty" :precision="2"
                                     :min="0"/>
                    </FormItem>
                </Col>
                <!-- 罚息金额 -->
                <Col :xs="24" :md="12" :lg="8">
                    <FormItem label="罚息金额">
                        <InputNumber style="width: 200px" disabled v-model="formData.penaltyAmt" :precision="2"
                                     :min="0"/>
                    </FormItem>
                </Col>
                <!-- 豁免金额 -->
                <Col :xs="24" :md="12" :lg="8">
                    <FormItem label="豁免金额">
                        <InputNumber style="width: 200px" disabled v-model="formData.exemptionAmt" :precision="2"
                                     :min="0"/>
                    </FormItem>
                </Col>
                <!-- 净逾期额 -->
                <Col :xs="24" :md="12" :lg="8">
                    <FormItem label="净逾期额">
                        <InputNumber style="width: 200px" disabled v-model="formData.overdueAmt" :precision="2"
                                     :min="0"/>
                    </FormItem>
                </Col>
                <!-- 减免比例 -->
                <Col :xs="24" :md="12" :lg="8">
                    <FormItem label="减免比例">
                        <InputNumber disabled
                                     style="width: 200px"
                                     :precision="2"
                                     :max="100"
                                     v-model="formData.reductionRatio"
                                     :formatter="value => `${value}%`"
                                     :parser="value => value.replace('%', '')"
                                     :min="0"
                        ></InputNumber>
                    </FormItem>
                </Col>
            </Row>
        </Form>
    </div>
</template>
<script>
    import {getBasicPenaltyInterest, getPenaltyExempt} from "_p/basic/api/contract/fee-waiver/penalty-exempt";
    import {getTitleFromDataDict, verifyErrorToView} from "_p/basic/assets/contract/js/utils";
    import {deepClone} from "@/libs/utils/ObjectClone";

    export default {
        props: {
            dataDict: {
                type: Object,
                required: true
            },
            isApprove: {
                type: Boolean,
                require: true
            },
            //对象参数包含：合同号码、角色类型
            Obj: {
                type: Object,
                required: true
            },
            pageParams: {
                type: Object,
                required: true
            }
        },
        data() {
            return {
                value1: null,
                readOnly: false,
                showForm: {
                    type: "",
                    phone: false,
                    address: false
                },
                all: '',
                oldData: {},
                formData: {
                    totalPenalty: null,
                    penaltyAmt: null,
                    exemptionAmt: null,
                    overdueAmt: null,
                    reductionRatio: null,
                    eliefDays: null,
                    managePenaltyExemptDetails: {}
                },
                formRules: {},
                tableHead: [
                    {
                        title: '客户姓名',
                        key: 'custName',
                        fixed: 'left',
                        width: 100
                    },
                    {
                        title: '合同号',
                        key: 'contractNo',
                        width: 100
                    },
                    {
                        title: '期数',
                        key: 'termNo',
                        width: 100
                    },
                    {
                        title: '逾期天数',
                        key: 'overdueDays',
                        width: 100
                    },
                    {
                        title: '罚息总计',
                        key: 'totalPenalty',
                        type: 'number',
                        slot: 'totalPenalty',
                        scale: 2,
                        width: 100
                    },
                    {
                        title: '罚息金额',
                        key: 'penaltyAmt',
                        slot: 'penaltyAmt',
                        type: 'number',
                        scale: 2,
                        width: 100
                    },
                    {
                        /** 真实豁免金额;银企直连异常豁免金额、单笔罚息豁免办理会累加 */
                        title: '累计豁免额',
                        key: 'exemptedAmt',
                        slot: 'exemptedAmt',
                        type: 'number',
                        scale: 2,
                        width: 100
                    },
                    {
                        title: '减免天数', // 自填
                        key: 'eliefDays',
                        slot: 'eliefDays',
                        width: 100,
                    },
                    {
                        title: '豁免金额', // 自填
                        key: 'exemptionAmt',
                        slot: 'exemptionAmt',
                        type: 'number',
                        scale: 2,
                        width: 100,
                    },
                    {
                        title: '减免比例', // 自填
                        key: 'reductionRatio',
                        slot: 'reductionRatio',
                        width: 100,
                    },
                    {
                        title: '净逾期额', // 自填
                        key: 'overdueAmt',
                        slot: 'overdueAmt',
                        type: 'number',
                        scale: 2,
                        width: 100,
                    },
                    {
                        /** 已收金额 */
                        title: '核销额',
                        key: 'receivedAmt', //amount_received
                        slot: 'receivedAmt',
                        type: 'number',
                        scale: 2,
                        width: 100
                    },
                    {
                        title: '还款日',
                        key: 'repaymentDate',
                        width: 100
                    },
                    {
                        /** 创建人 */
                        title: '创建人',
                        key: 'createBy',
                        width: 100
                    },
                    {
                        /** 创建时间 */
                        title: '创建时间',
                        key: 'createTime',
                        width: 150
                    },
                    {
                        title: '状态',
                        key: 'status',
                        width: 100,
                        slot: 'status',
                    },
                    {
                        /** 完成日期;此条罚息结清日期 */
                        title: '结束日期',
                        key: 'completionDate',
                        width: 150
                    }

                ],
                tableData: []
            };
        },
        computed: {},
        watch: {},
        created() {
        },
        mounted() {
            if (this.Obj.process === "process") {
                this.readOnly = this.Obj.process === "process" ? true : false;
            }
            if (this.Obj.editFlag) {
                this.getPenaltyExempt();
            } else {
                this.init();
            }
        },
        methods: {
            init() {
                if (this.pageParams)
                    this.getBasicInfo(this.pageParams.contractNo);
            },
            getBasicInfo(data) {
                if (!data) return;
                if (!this.Obj.editFlag) {
                    getBasicPenaltyInterest(data).then(res => {
                        if (res.code === "0000") {
                            // this.tableData = res.data;
                            this.sortData(res.data);
                        }
                    });
                }
            },
            getTitle(type, val) {
                let data = this.dataDict[type + "Dict"] || [];
                return getTitleFromDataDict(data, val);
            },
            getPenaltyExempt() {
                getPenaltyExempt(this.Obj.id).then(res => {
                    if (res.code === "0000") {
                        this.formData = deepClone(res.data);
                        this.sortData(res.data.managePenaltyExemptDetails);
                    }
                });

            },
            // 数据处理 禁用状态
            sortData(tableData) {
                let isDisable = false;
                Array.isArray(tableData) && tableData.forEach(e => {
                    e._rowDisabled = isDisable;
                    if (isDisable) {
                        e.exemptionAmt = 0;
                        e.reductionRatio = 0;
                        e.eliefDays = 0;
                    }
                    if (e.exemptionAmt !== e.penaltyAmt) {
                        isDisable = true
                    }
                })
                this.tableData = tableData
            },
            /*
             * formData 数据验证 验证通过后 将数据传回父级处理  (保存/提交/审核 通用)
             * @param {String} funcName 回传给父级的方法 (注意父级需要传方法)
             * @param {Object} [data]   父级带来的数据
             */
            formValidate(funcName, data) {
                if (!funcName) return;

                this.$refs.formData.validate(valid => {
                    if (valid) {
                        let d = Object.assign({}, data, this.formData, this.Obj);
                        if (d.managePenaltyExemptDetails) {
                            d.managePenaltyExemptDetails = null;
                        }
                        this.$emit(funcName, d);
                    } else {
                        this.$Message.error("验证不通过!");
                        this.$emit("closeSpin");
                        verifyErrorToView(this.$refs.formData.fields);
                    }
                });
            },
            handleSummary({columns, data}) {
                const sums = {};
                columns.forEach((column, index) => {
                    const key = column.key;
                    if (index === 0) {
                        sums[key] = {
                            key,
                            value: '总计'
                        };
                        return;
                    }
                    const values = data.map(item => Number(item[key]));
                    if (index === 4 || index === 5 || index === 6 || index === 8 || index === 10) {
                        const v = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[key] = {
                            key,
                            value: v.toFixed(2)
                        };
                        if (key === 'totalPenalty') {
                            this.formData.totalPenalty = v;
                        }
                        if (key === 'penaltyAmt') {
                            this.formData.penaltyAmt = v;
                        }
                        if (key === 'exemptionAmt') {
                            this.formData.exemptionAmt = v;
                        }
                        if (key === 'overdueAmt') {
                            this.formData.overdueAmt = v;
                        }
                        this.formData.reductionRatio = this.formData.exemptionAmt * 100 / this.formData.penaltyAmt;
                        this.formData.managePenaltyExemptDetails = this.tableData;
                    } else if (index === 9) {
                        let reductionRatio = this.formData.reductionRatio;
                        sums[key] = {
                            key,
                            value: reductionRatio.toFixed(2),
                        };
                    } else {
                        sums[key] = {
                            key,
                            value: ''
                        };
                    }
                });

                return sums;
            },
            // 计算 豁免金额 和 减免比例 & OverdueAmt
            getReductionRatioAndExemptionAmt(row, index, type) {
                if (!row) return;
                const {totalPenalty, penaltyAmt, overdueDays, eliefDays, reductionRatio, exemptionAmt} = row;
                if (!totalPenalty || !overdueDays) return;
                let r = reductionRatio || 0, e = exemptionAmt || 0, o = 0, d = eliefDays || 0,
                    data = deepClone(this.tableData);

                if (type === 'eliefDays') {
                    e = penaltyAmt / overdueDays * eliefDays;
                    r = e / penaltyAmt * 100;
                }
                if (type === 'reductionRatio') {
                    e = penaltyAmt * reductionRatio / 100;
                    // d = e / (penaltyAmt / overdueDays);
                }
                if (type === 'exemptionAmt') {
                    r = exemptionAmt / penaltyAmt * 100;
                    // d = exemptionAmt / (penaltyAmt / overdueDays);
                }
                o = penaltyAmt - e;

                data[index] = Object.assign({}, row, {
                    reductionRatio: r ? Number(r.toFixed(2)) : r,
                    exemptionAmt: e ? Number(e.toFixed(2)) : e,
                    // eliefDays: d ? Number(d.toFixed(0)) : d,
                    overdueAmt: o
                });
                this.sortData(data)
                // this.tableData = data;
            },

        }
    };
</script>
<style lang="less" scoped>
    .business form {
        width: 100%;
    }

    .table-foot {
        padding-top: 8px;
        padding-bottom: 16px;
    }
</style>
